package cn.com.xyc.rabbitmq;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.ConsumerCancelledException;
import com.rabbitmq.client.QueueingConsumer;
import com.rabbitmq.client.ShutdownSignalException;

public class ReceiveLogsToSave {
	private final static String EXCHANGE_NAME = "ex_log";

	public static void main(String[] args) throws IOException,
			ShutdownSignalException, ConsumerCancelledException,
			InterruptedException {
		// 创建连接和频道
		ConnectionFactory factory = new ConnectionFactory();
		factory.setHost("192.168.1.128");
		factory.setUsername("xyc");
		factory.setPort(5672);
		factory.setPassword("123456");
		Connection connection = factory.newConnection();
		Channel channel1 = connection.createChannel();
		// 声明转发器和类型
		channel1.exchangeDeclare(EXCHANGE_NAME, "fanout");

		// 创建一个非持久的、唯一的且自动删除的队列
		String queueName = channel1.queueDeclare().getQueue();
		// 为转发器指定队列，设置binding
		channel1.queueBind(queueName, EXCHANGE_NAME, "");
		System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
		QueueingConsumer cousumer = new QueueingConsumer(channel1);
		channel1.basicConsume(queueName, true, cousumer);

		while (true) {
			QueueingConsumer.Delivery delivery = cousumer.nextDelivery();
			String message = new String(delivery.getBody());
			print2File(message);
		}

	}

	public static void print2File(String msg) {
		String dir = ReceiveLogsToSave.class.getClassLoader().getResource("")
				.getPath();
		String logFileName = new SimpleDateFormat("yyyy-MM-dd")
				.format(new Date());
		File file = new File(dir, logFileName + ".txt");
		try {
			FileOutputStream fos = new FileOutputStream(file, true);
			fos.write((msg + "\r\n").getBytes());
			fos.flush();
			fos.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
